package com.lsh.oms.provider.service.endpoint;

import com.alibaba.dubbo.config.annotation.Service;
import com.lsh.base.common.model.CommonResult;
import com.lsh.oms.core.records.core.ReturnResult;
import com.lsh.oms.core.records.core.ReturnResultRepository;
import com.lsh.oms.core.service.tool.Criteria;

import javax.annotation.Resource;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.util.Map;

@Path("return-results")
@Service(protocol = "rest", timeout = 30000)
public class ReturnResultsResource implements com.lsh.oms.api.endpoint.core.ReturnResultsResource {

    @Resource
    private ReturnResultRepository returnResults;

    @GET
    @Produces({MediaType.APPLICATION_JSON})
    @Override
    public Response query(@Context UriInfo uriInfo,
                          @DefaultValue("1") @QueryParam("page") long page,
                          @DefaultValue("20") @QueryParam("page-limit") long limit) {
        return Response
                .ok(returnResults.query(Criteria.of(uriInfo), page, limit))
                .build();
    }

    @GET
    @Path("{id}")
    @Produces({MediaType.APPLICATION_JSON})
    @Override
    public Response find(@PathParam("id") Long id,
                         @QueryParam("details-required") @DefaultValue(value = "true") boolean detailsRequired) {
        return Response
                .ok(findReturnResult(id))
                .build();
    }

    @GET
    @Path("summary")
    @Produces({MediaType.APPLICATION_JSON})
    @Override
    public Response summary(@Context UriInfo uriInfo) {
        return Response.ok(returnResults.summary(Criteria.of(uriInfo))).build();
    }

    @POST
    @Path("{id}/payment-notify")
    @Consumes({MediaType.APPLICATION_JSON})
    @Produces({MediaType.APPLICATION_JSON})
    @Override
    public Response paymentNotify(@PathParam("id") Long id, Map<String, Object> request) {
        findReturnResult(id).paymentNotify(request);
        return Response.ok(CommonResult.success()).build();
    }

    @GET
    @Path("{id}/relations")
    @Produces({MediaType.APPLICATION_JSON})
    @Override
    public Response relations(@PathParam("id") Long id) {
        return Response
                .ok(findReturnResult(id).relations())
                .build();
    }

    private ReturnResult findReturnResult(Long id) {
        return returnResults.find(id).orElseThrow(NotFoundException::new);
    }
}
